/**
 * @file VenuesService.ts
 * @description Venue service for managing venue data
 * @date 2024-6-4
 * @version 1.0.0
 */

import VenueModel, { IVenue } from "../models/VenueModel";

class VenuesService {
  /** 创建场馆 */
  public async createVenue(params: IVenue) {
    try {
      const venue = await VenueModel.create(params);
      return venue;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 查询场馆列表 */
  public async getVenueList(params: {
    pageSize: number;
    pageIndex: number;
    venueName?: string;
    address?: string;
  }) {
    try {
      const { pageSize, pageIndex, venueName, address } = params;
      const filterRules: any = {};
      if (venueName) {
        filterRules.venueName = { $regex: new RegExp(venueName) };
      }
      if (address) {
        filterRules.address = { $regex: new RegExp(address) };
      }
      const total = await VenueModel.find().countDocuments();
      const list = await VenueModel.find()
        .where(filterRules)
        .skip((pageIndex - 1) * pageSize)
        .limit(pageSize)
        .select([
          "venueId",
          "venueName",
          "address",
          "status",
          "comment",
          "createdAt",
          "updatedAt",
        ])
        .exec();
      return {
        total,
        pageIndex,
        pageSize,
        list,
      };
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 更新场馆信息 */
  public async updateVenue(params: IVenue) {
    try {
      const venue = await VenueModel.findOneAndUpdate(
        { venueId: params.venueId },
        params,
        {
          new: true,
        }
      );
      return venue;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 删除场馆 */
  public async deleteVenue(venueId: string) {
    try {
      const venue = await VenueModel.findOneAndDelete({ venueId });
      return venue;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 获取场馆信息 */
  public async getVenueById(id: string) {
    try {
      const venue = await VenueModel.findOne({ venueId: id }).select([
        "venueId",
        "venueName",
        "address",
        "status",
        "comment",
        "createdAt",
        "updatedAt",
      ]);
      return venue?.toObject();
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
}

export default new VenuesService();
